package cc.lucien.controller;

import cc.lucien.entity.Admin;
import cc.lucien.entity.CheckModel;
import cc.lucien.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;


@Controller
@RequestMapping("/login")
@SessionAttributes({"admin"})
public class LoginController {

    @Autowired
    private AdminService adminService;

    /**
     * 去到登录页面
     * @return
     */
    @GetMapping("/toLogin")
    public String toLogin() {
        return "login";
    }

    /**
     * 登录校验
     * @param checkModel
     * @param request
     * @param map
     * @return
     */
    @PostMapping("/check")
    public String check(CheckModel checkModel, HttpServletRequest request, Map<String, Object> map) {
        String checkcode = (String) request.getSession().getAttribute("checkcode");
        // 校验验证码的正确性
        if (!checkcode.equals(checkModel.getCheckcode())) {
            // 说明验证码错误
            request.setAttribute("msg", "验证码错误");
            return "login";
        }
        Admin admin = new Admin();
        admin.setUsername(checkModel.getUsername());
        admin.setPassword(checkModel.getPassword());
        Admin result = adminService.findByUsernameAndPassword(admin);
        // 如果返回的数据不为 null 说明数据库中由该账户且密码正确
        if (result == null) {
            request.setAttribute("msg", "账号或密码错误");
            return "login";
        }
        // 将查询出来的用户添加到 request以及session会话域中
        map.put("admin", result);
        // 管理员主页
        return "redirect:/admin/main";
    }
}
